package com.kerio.observer.core;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by hetao on 2018/3/21.
 */
public class EventListener {
    protected Map<Enum,Event> events=new HashMap<Enum,Event>();

    public void addListener(Enum eventType,Object target,Method callBack){
        //注册事件
        //用反射调用这个方法
        events.put(eventType,new Event(target, callBack));
    }

    private void trigger(Event e){
        e.setSource(this);
        e.setTime(System.currentTimeMillis());

        try {
            e.getCallBack().invoke(e.getTarget(),e);
        } catch (IllegalAccessException e1) {
            e1.printStackTrace();
        } catch (InvocationTargetException e1) {
            e1.printStackTrace();
        }

    }

    protected void trigger(Enum call){
        if(!this.events.containsKey(call))
            return;
        trigger(this.events.get(call).setTrigger(call.toString()));
    }
}
